var userAgent = navigator.userAgent;
var POPUP_NAME = "list";
var isWindowsCE = false;
//var isChrome = /chrome/.test( navigator.userAgent.toLowerCase() );
if (userAgent.indexOf("Windows CE") > -1) {  
	isWindowsCE = true;
}
		
		
//---------------------------------------------------------------------------
// Gestione Finestra
var form = document.forms[0];
var waitRefresh = false;
var canExecLookupLC = true;

//------- funzione focus e lista valori-----
var nameProperty;
var nameWidget;
 
var printerTarget = 'view';

var disabledImages = new Array();

var disableKey = false;

var isDelayedAction = false;

var defaultDelayedActionTime = 25;

function doPreloadDisabledImages() {
	var str="";
	var i;
	for (i=0; i<document.images.length; i++) {
		if (document.images[i].parentNode.nodeName.toUpperCase()=="BUTTON") {
			var tmp = document.images[i].src;
			var index = tmp.lastIndexOf('_disabled.');
			if (index<0) {
				index = tmp.lastIndexOf('.');
		  	  	tmp = tmp.substring(0,index) + '_disabled' + tmp.substring(index);
		  	  	if (disabledImages[tmp]==null) {
		  	  		disabledImages[tmp] = new Image();
		  	  		disabledImages[tmp].src = tmp;
		  	  	}
			}
		}
	}
}

function doOnLoad(nw) {
  form = document.forms[0];
  if (this['customOnLoad']) {
    customOnLoad();
  }
  moveMenuButtons();
  doPreloadDisabledImages();
  if(nw!=null)
   nameWidget=nw;
  setFocusWidget(nameWidget);
} 

function clearWidget(widget) {
	form[widget].value = '';
	if (form[widget].onchange)
		form[widget].onchange();
  else if (form[widget].onblur) 
  	form[widget].onblur();		
}

//---------------------------------------------------------------------------
// Gestione Finestra
//
//Chiudi
function chiudi(){
	if(!window.opener.canExecLookupLC)
	{
		window.opener.canExecLookupLC = true;
	}
		
  window.close();
}
//Stampa
function stampa(){
  self.print();
  self.close();
}

//-------Introdotto da ADT
// stati del cursore: default(freccia), wait(clessidra)
function setCursor(mode) {
	document.body.style.cursor=mode;
	for (var i=0; i< form.elements.length; i++)
		form.elements[i].style.cursor = mode;
}

//-----------------------------------------------------------------------------
// Gestione Action
//

function doAction(action,noLock,delay){
	if(delay != undefined) {
		setTimeout(function() {doInternalAction(action,noLock);}, delay);
	} else if(isDelayedAction){
		setTimeout(function() {doInternalAction(action,noLock);}, defaultDelayedActionTime);
	} else {	
		doInternalAction(action,noLock);
	}
}

function doInternalAction(action,noLock) {
  var workflow = false;
  if (!doBeforeAction(action,null)) 
    return;

  if (form["FOCUS"]) {
    form["FOCUS"].value = nameWidget;
  }
  
  if(action!=null)
	  if(action.indexOf("WORKFLOW",0)==0)
		  workflow = true; 
  
  if((action=="CONFIRM")||(workflow))
   if (!controlFields())
     return;
  //if(!noLock)
   //setCursor('wait');
  formSubmit(noLock,action);   
  ActionListener.fire(action, $(form).attr("action"));
}

function doActionAndIndex(action,index,noLock) {
  if (!doBeforeAction(action,index)) 
    return;

  form["INDEX"].value = index;
  if (form["FOCUS"]) {
    form["FOCUS"].value = nameWidget;
  }
  
  if(action=="CONFIRM")
	  if (!controlFields())
		     return;
  formSubmit(noLock,action);   
}

//Questo metodo puo' essere reimplementato delle pagine jsp
// return 
//    true - continua il normale comportamento 
//    false -  viene interrotto il flusso di esecuzione
function doBeforeAction(action,index) {
  return true;
}

// Blocca tutti i widget
function formSubmit(noLock,action) {	
	//alert('formSubmit');

	setTimeout("delayedSubmit("+ (noLock==true) +",'"+action+"')", 100);
	return true;
}

function delayedSubmit(noLock,action) {
	//alert('delayedSubmit');
  if (noLock) {
		// NO LOCK
	} else {
		if (isWindowsCE) {
			//alert('delayedSubmit:isWCE');
			lockWidgets(true);
		} else {
			//alert('delayedSubmit:isNotWCE');
			//lockUI();
		}	
	}	
	//alert(action);
	//alert(document.forms[0].action);
  if(action)
	  document.forms[0].action = action;
  document.forms[0].submit();	
}

function setClass(object,classValue) {
	var attr = object.getAttributeNode("class");
	if (attr) {
		attr.value = classValue;
	} else {
		object.setAttribute("class",classValue);
	}
}

function lockButton(button, lock) {
    if (!isWindowsCE){
  	  var list = button.getElementsByTagName('img');
  	  for (var j=0; j<list.length; j++) {
  	  	if (lock && !button.disabled) {
	  	  	var index = list.item(j).src.lastIndexOf('.');
	  	  	list.item(j).src = list.item(j).src.substring(0,index) + '_disabled' + list.item(j).src.substring(index);
  	  	} else if (!lock && button.disabled) {
  		  	var index = list.item(j).src.lastIndexOf('_disabled.');
	  	  	list.item(j).src = list.item(j).src.substring(0,index) + list.item(j).src.substring(index+9,list.item(j).src.length);
  	  	}
  	  }
  	  button.style.cursor = lock ? 'default' : 'pointer';
    }
    button.disabled = lock;
    button.readOnly = lock;
}
	
function lockInput(input, lock, methods) {
	input.readOnly = lock;
	input.disabled = lock;
	setClass(input,!lock?"form_01":"lockedField");
	if (lock) {
		input.value = '';
	}
	if (methods && input.onchange)
		input.onchange();
	if (methods && input.onblur)
		input.onblur();
}
	

lockUI = function(icona, testo) {
  var msg = ' Attendere prego ...';
  var ico = 'images/busy.gif';
  if(icona != null)
    ico = icona;
  if(testo != null)
    msg = testo;
  disableKey = true;

  var closeMessage= '';
  var viewCloseMessage = 'false';
  try{ 
  	//viewStopWaiting settato nella jbfBaseLayout
	viewCloseMessage = viewStopWaiting;  
  } catch(e) {
	  //caso di pagine che nn hanno la jbfBaseLayout
  }
  if( viewCloseMessage== 'true' ){
	 closeMessage= '<div style="text-align: right;"><a href="#" onClick="javascript:doAction(\'KILL_ACTION\');unlockUI();"  >Annulla</a></div>';
  }  
  var  htmlCode = '<div style="padding: 10px; padding-top: 15px; padding-bottom: 15px; margin: 0px; font-size: 18px; font-weight: bold;">' + 
	'<img src="'+ico+'" style="vertical-align: middle"/>'+msg+'</div>'+ closeMessage;
  
  $.blockUI({message: htmlCode});
};

unlockUI = function(){
  $.unblockUI();
}
	
function lockWidgets(lock) {
  for (var i = 0; i < form.elements.length; i++) {
    if (form.elements[i].type == "button") {
    	lockButton(form.elements[i],lock);
    }	
  }	
  var a = document.getElementsByTagName("a");
  for (var i=0; i< a.length; i++) {
	a[i].removeAttribute("href");
	a[i].setAttribute("onclick","javascript:void(0);");
  }
  var span = document.getElementsByTagName("span");
  for (var i=0; i< span.length; i++) {
	span[i].setAttribute("onclick","javascript:void(0);");
  }
  if(!isWindowsCE)
    setCursor('wait');
}	

// Funzione da sovrascrivere nel caso si voglia eseguire delle azioni personalizzate
// prima del doActionWindow. Funziona allo stesso modo del doBeforeAction.
// Deve tornare un booleano.
function doBeforeActionWindow(action,target,onCloseAction,extraData){
	return true;
}

// Esegue l'azione specificata generando l'output su un'altra finestra
//l'elemento data viene usato per la find3lookup passando il nome della lookup
function doActionWindow(action,target,onCloseAction,extraData,size,showMenuBar, data) {	
  if(!doBeforeActionWindow(action,target,onCloseAction,extraData))
	return;
	
  if(action=="CONFIRM")
	  if(!controlFields())
		  return;
  if(data){
	  form["DATA"].value = data;
  }
  if(target == null || target=="")
    target = "win" + (new Date()).getTime();
  form["ACTION"].value = action;
  if (size == null)
  	size = windowsSize();
  var ss = getSubmitArrays();
  if (extraData)
  	ss = extraDataToArrays(extraData,ss);

	var showMenu = 'no';
  if (showMenuBar) {
  	showMenu = 'yes';
  }	
  target = target.replace('[', '_');
  target = target.replace(']', '_');

  var win1 = window.open('',target,'screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar=' + showMenu + ',scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes,'+size);
  
  if (extraData) {
    // ATTENZIONE! Qui c'� un problema noto: se in un campo ci sono dei caratteri "strani",
    // come caratteri accentati, quando si ritorna alla pagina chiamata questi vengono
    // convertiti in maniera sbagliata, ovvero vengono scritti come UTF-8 ma poi
    // inviati (postati) con codifica ISO-8859-1.
    
    //Aggiungo il flag per non rendere visibile il menu
    ss[0][ss[0].length] = "MENU_HIDE";
    ss[1][ss[1].length] = "ON";
    postData(win1.document,form.action,ss[0],ss[1]);
  } else {
    targhetOld = form.target;
    try {
      form.target = target;
      form.submit();
    } finally {
      form.target = targhetOld;
    }
  }
  if (onCloseAction)
    this.onCloseAction = onCloseAction;
}


// Esegue l'azione specificata generando l'output su un'altra finestra
function doPostActionWindow(action,target,onCloseAction,size,showMenuBar) {

  if(target == null || target=="")
    target = "win" + (new Date()).getTime();
  form["ACTION"].value = action;
  if (size == null)
  	size = windowsSize();

	var showMenu = 'no';
  if (showMenuBar) {
  	showMenu = 'yes';
  }	
  
  targhetOld = form.target;
  try {
    form.target = target;
    form.submit();
  } finally {
    form.target = targhetOld;
  }
    
  if (onCloseAction)
    this.onCloseAction = onCloseAction;
}


// Esegue l'azione specificata generando l'output su un'altra finestra senza fare il Get degli attributi
function doActionWindowNoGet(action,target,onCloseAction,size,showMenuBar) {
  if(target == null || target=="")
    target = "win" + (new Date()).getTime();
  form["ACTION"].value = action;
  
  var showMenu = 'no';
  if (showMenuBar) {
  	showMenu = 'yes';
  }	
  
  if (size == null)
  	size = windowsSize();
  win1 = window.open(form.action+"?ACTION="+action,target,'screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar='+showMenu+',scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes,'+size);
  if (onCloseAction)
    this.onCloseAction = onCloseAction;
}

function doActionAndIndexWindow(action,index,target,onCloseAction,showMenuBar,extraData) {
  if(target == null || target=="")
    target = "win" + (new Date()).getTime();
  form["ACTION"].value = action;
  form["INDEX"].value = index;
  
  var showMenu = 'no';
  if (showMenuBar) {
  	showMenu = 'yes';
  }	
  
  //target = target.replace(/ /g,"_");
  win1 = window.open('',target,'screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar='+showMenu+',scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes,'+windowsSize());
  targhetOld = form.target;
  try {
    form.target = target;
  
	  if (extraData) {
	  	var ss = extraDataToArrays(extraData,ss);
	  	var names = ss[0];
	  	var values = ss[1];
	  	
	    for (var i = 0; i < names.length; i++) {
	      var inputElement = document.createElement("input");
	      inputElement.type = "hidden";
	      inputElement.name = names[i];
	      inputElement.value = values[i];
	      form.appendChild(inputElement);
	    }
	  }
  
    form.submit();
  } finally {
  	form.target = targhetOld;
  }
  if (onCloseAction)
    this.onCloseAction = onCloseAction;
}


function windowOpen(href,target) {
  window.open(href,target,'screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar=no,scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes,'+windowsSize());  
}


function windowsSize() {
	return " width="+(screen.width-10)+",height="+(screen.height-80);
}

function doRefresh(properties) {
  waitRefresh = true;
  if (properties != null)
    form["PROPERTIES"].value = properties;

  doAction("REFRESH");
}

function doClearAction() {
	form["ACTION"].value = "";
	  doAction("");
	}

function doDelete(prefixActionHandlerName) {
  if (confirm("Vuoi cancellare il record?")){
	if(prefixActionHandlerName)
	  doAction(prefixActionHandlerName+".DELETE");
	else
	  doAction("DELETE");	
  }
}

var onCloseCallback;

// Chiude una finestra dopo
// - aver notificato al controller l'action se presente
// - notificato all'opener la chiusura
function doClose(action) {
  //Notifica chiusura controller
  if (action)
    sendAction(action);

  //Notifica chiusura opener
  try {
   if (opener.onCloseAction) {
    opener.doAction(opener.onCloseAction);
   } else if (opener.onCloseCallback) {
     opener.onCloseCallback();
   }
  } catch(e) {
  }

  //Chiude finestra
  close();
}


function doReload(target) {
	var currentName ='form' +(new Date()).getTime();
	$('body').append('<form '+((target)?'target="'+target+'"':'' )+ 'id='+currentName+'> </form>');
	$('#'+currentName)[0].submit();
 }

function doFindResultPrint(allRows,printActionPrefix) {
	if (printActionPrefix==null) {
		printActionPrefix="";
	}else{
		printActionPrefix += ".";
	}	
		
	var width = screen.availWidth-10;
	var height = screen.availHeight-50;
	var appletWidth = width-20;
	var appletHeight = height-60;
	var menu;
	if ((printerTarget=='txt') || (printerTarget=='html') || (printerTarget=='xml') || (printerTarget=='csv') || (printerTarget=='xls')) {
		menu = 'yes';
		height = height-70;
		appletHeight = appletHeight-70;
	} 
	else {
	  menu = 'no';
	  if (printerTarget=='print') {
	  	width = 1;
	  	height = 1;
	  	appletWidth = 1;
	  	appletHeight = 1;
	  }
	}

	var ss = getSubmitArrays();
	
	var idx= $.inArray("ACTION", ss[0]);
	if(idx!=-1)
		ss[1][idx] = printActionPrefix + "PRINT.FINDRESULT";
	else {
		ss[0][ss[0].length] = "ACTION";
		ss[1][ss[1].length] = printActionPrefix+"PRINT.FINDRESULT";
	}
	//controllo se nell'array e' presente TIPO_STAMPA (la printButtonBar usa una form a se' non mappata nella getSubmitArrays) 
	var idxTs= $.inArray("TIPO_STAMPA", ss[0]);
	if(idxTs<0){
		ss[0][ss[0].length] = "TIPO_STAMPA";
		ss[1][ss[1].length] = printerTarget;
	}
	
	ss[0][ss[0].length] = "WIDTH";
	ss[1][ss[1].length] = appletWidth;
	
	ss[0][ss[0].length] = "HEIGHT";
	ss[1][ss[1].length] = appletHeight;
	
	ss[0][ss[0].length] = "ALLROWS";
	ss[1][ss[1].length] = allRows ? "S" : "N";
	
	var win1 = window.open('','FINDRESULT','width='+width+',height='+height+',screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar='+menu+',scrollbars=yes,titlebar=no,alwaysRaised=yes,status=yes');
	postData(win1.document,form.action,ss[0],ss[1]);
	
}

//----------------- TAsti funzione ------------------
var isIE = false, isN4 = false, isN6 = false;
var validateError = false;


// Function init

 if (document.all) {
  isIE = true;
  document.onkeydown = checkKeyDown;
	document.onkeyup = checkKeyUp;
    }
 else {
  isN6 = true;
  document.onkeydown = checkKeyDown;
	document.onkeyup = checkKeyUp;
}    

var altKey = false,shiftKey = false, ctrlKey = false;

function checkKeyDown(e) {
  
  if(disableKey)	
	return;
	
  if (isIE) {
    e = window.event;
  }
  if (e.keyCode)
    ch = e.keyCode;
	else if (e.which)
	  ch = e.which;
	
    var searchButton = false;
  
	if (ch < 16 || ch > 18) {
		var key = "";
		if (e.ctrlKey) { 
			key += "CTRL+";
			searchButton = true;
		}
		if (e.shiftKey) {
			key += "SHIFT+";
			//searchButton = true;
		}
		if (e.altKey) {
			key += "ALT+";
			searchButton = true;
		}

		if (ch >= 112 && ch <= 123) {
			key += "F" + (ch-111);
			searchButton = true;
		} else if (ch == 27) {
	  	  key += "ESC";
	  	  searchButton = true;
		}else {
	  	  key += String.fromCharCode(e.keyCode);
		}

		button = (searchButton) ? getButtonByShortcut(key) : null;
		
		if (button != null && !button.disabled) {
			validateError = false;
			buttonOnMouseDown();
			
			if(button.getAttribute("type") != null) {
				if(button.getAttribute("type").toUpperCase() != "HIDDEN") {
					button.focus();
				}
			}
			
			if(validateError == false) {
				button.onclick();
		  }
		}

	  if (ch != 0 && ch!=122 && (ch >= 112 && ch <= 123) || ch==27) {
			if (isN6 || isN4) {
				lastkey = '';
				e.preventDefault();
				e.cancelBubble = true;
				return false
			}
			if (isIE) {
				event.keyCode = 0;
			  return false;
		  }
	  }
	}
	
	shiftKey = (ch == 16);
	ctrlKey = (ch == 17);
	altKey = (ch == 18);

}

function checkKeyUp(e) {
  
  if(disableKey)	
	return;	
	
  if (isIE) {
    e = window.event;
  }
  if (e.keyCode)
    ch = e.keyCode;
	else if (e.which)
	  ch = e.which;
	
	if (ch == 16) shiftKey=false;
	if (ch == 17) ctrlKey=false;
	if (ch == 18) altKey=false;
}

function getButtonByShortcut(key){
	var q = $("[accelerator='"+key+"']");
	if (q.length > 0)  {
	  return q.get(0);
	}
	
	//TODO rimuovere
	f = document.forms[0];
	if (f) {
		for (var i = 0; i < f.elements.length; i++) {
			if (f.elements[i].getAttribute("accelerator")==key) {
				return f.elements[i];
			}
		}
	}
	return null;
}

function doReport(target,action) {
  printerTarget=target;
  doAction(action);
}

function doLookup() {
  if(nameProperty!=null){
    if(form[nameProperty+"_l"]!=null){
      actionButton(nameProperty+"_l");
    } else {
      lookupOnClick(nameProperty);
    }  
  }
}

// Function checkKey
function checkKey(e) { 
 var ch = 0;
  
 if (isN6 || isN4) {
  
  ch = (e.keyCode) ? e.keyCode : (e.charCode) ? e.charCode :e.which;
  if (e.keyCode != 0 && (ch >= 112 && ch <= 123) || ch==27) {
    functionkey(ch);
    lastkey = '';
    e.preventDefault();
    e.cancelBubble = true;
    return false;
   }    
 }     
      
 if (isIE) {
  ch = window.event.keyCode;
  if (ch >= 112 && ch <= 123 || ch==27) { 
   functionkey(ch);
   event.keyCode = 0;       
   return false; 
  }
 } // if (isIE)     
}

function enterPressed(e) {
  var characterCode;
  if(e && e.which)
  {    
    characterCode = e.which;
  }
  else 
  {
    characterCode = e.keyCode;
  }
  if (characterCode == 13)
	  return true;
	else
	  return false;
}

// trap F1 for IE browser and stop default behaviour  
document.onhelp = function (){
 event.cancelBubble = true;
 event.returnValue = false;
}
  
function functionkey(ch2) {
 if(disableKey)	
	return;
		
 switch (ch2) 
 {
 	case 27:
 	 actionButton('BTN_EXIT');
   break;
  case 112:
   doHelp();
   break;
  case 113:
   doLookup();
   break;
  case 114:
   actionButton('BTN_INSERT');
   break;
  case 115:
   actionButton('BTN_CONFIRM');
   break;
  case 116:
   actionButton('BTN_DELETE');
   break;
  case 117:
	 doReport('print','BTN_STAMPA');
   break;
  case 119:
   actionButton('BTN_CANCEL');
   break;
  case 118:
	 doReport('view','BTN_STAMPA');
   break;
  case 120:
   break;
  case 121:
   break;
  case 122:
   break;
  case 123: //F12
   doActionWindow('INFO','info');
   break;
 }     
}

 function actionButton(nomeButton){
 	var widget = form[nomeButton];
 	if(widget!=null && !widget.disabled) {
 	 widget.onclick();
 	}
 }
  
 //------- funzione focus per lista valori-----
 function setPropertyFocus(widget,name){
 	nameWidget=widget.name;
 	if (name) {
   	  nameProperty=name;
 	}  else {
   	  nameProperty=widget.name;
 	}
 }  


//---------------------------------------------------------------------------
// Gestione DataFrame
// Viene usato il primo frame della window
function sendData(controller,data,action,names,values) {
  method = '';
  //Se spedisco troppi campi forzo il post
  if (names) {
    if (names.length > 10)
      method = ' method="post" ';
  }
  var fd = window.frames[0].document;
  fd.open();
  fd.write('<HTML><BODY><FORM NAME="dataForm" ACTION="'+controller+'" '+method+'  >\n');
  fd.write('<INPUT TYPE="HIDDEN" NAME="DATA" VALUE="'+data+'">\n');
  fd.write('<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="'+action+'">\n');
  if (names) {
    for (var i = 0; i < names.length; i++) {
       value = values[i];
       if (value != null && value.replace)
         value = value.replace(/\"/g,'&quot;');
      fd.write('<INPUT TYPE="HIDDEN" NAME="'+names[i]+'" VALUE="'+value+'">\n');
    }
  }
  fd.write('</FORM></BODY></HTML>\n');
  fd.close();
  
  try{
  	if (fd.charset) {
    	fd.charset = "ISO-8859-15";
    }
  }catch(e){}
  
  fd.forms[0].submit();
}

function postData(doc,controller,names,values) {
  doc.open();
  doc.write('<HTML><BODY><FORM NAME="dataForm" ACTION="'+controller+'" method="post">\n');
  if (names) {  
    for (var i = 0; i < names.length; i++) 
      doc.write('<INPUT TYPE="hidden" id="F' + i + '" NAME="'+names[i]+'">\n');
  }    
  doc.write('</FORM></BODY></HTML>\n');
  doc.close();
  for(var i=0; i<names.length; i++)
  	doc.getElementById('F' + i).value = values[i];
  	
  try{  	
  	if (fd.charset) {
    	fd.charset = "ISO-8859-15";
    }
  }catch(e){}
  	
  doc.forms[0].submit();
}

function sendAction(action) {
  var fd = window.frames[0].document;
  fd.open();
  fd.write('<HTML><BODY><FORM NAME="dataForm" ACTION="'+form.action+'">');
  fd.write('<INPUT TYPE="HIDDEN" NAME="ACTION" VALUE="'+action+'">');
  fd.write('</FORM></BODY></HTML>');
  fd.close();
  
  try{
  	if (fd.charset) {
    	fd.charset = "ISO-8859-15";
  	}
  }catch(e){}
  
  fd.forms[0].submit();
}

//---------------------------------------------------------------------------
// Gestione liste valori
//
var widgets;

var valueListResultCallback;

function valueListResult(values) {
  if (valueListResultCallback) {
	  valueListResultCallback(values)  
  } else if(widgets != null) {
	  for (var i = 0; i < widgets.length; i++) {
		    form[widgets[i]].value = values[i];
	  }
		  //chiamo l'onchange dei widget se presente
	  triggerOnchangeOnLookupWidgets(widgets);
  }
}
/*
 * Chiama l'onchange nei widget passati ( chimanato in seguito alla
 * scelta di un lookup)
 */
function triggerOnchangeOnLookupWidgets(widgets) {
	for (var i = 0; i < widgets.length; i++) {
		if (form[widgets[i]].onchange) {
			// Begin -- serve solo nella parte dinamica
			if (String(form[widgets[i]].onchange).indexOf("resizeLookup") != -1)
				resizeLookup(form[widgets[i]]);
			// End -- serve solo nella parte dinamica	
			if (String(form[widgets[i]].onchange).indexOf("noListValidate()") != -1) 
				continue;
			form[widgets[i]].onchange();
		} else if (form[widgets[i]].onblur) {
			if (String(form[widgets[i]].onblur).indexOf("noListValidate()") != -1) 
				continue;
			form[widgets[i]].onblur();
		}
	}
}
	
function valueListNull(queryName,filtersName,widgetName,targetWidgetName,controllFilters) {
 insert=true;
 for (var i = 0; i < controllFilters.length; i++) {
   for (var j = 0; j < filtersName.length; j++) {
    if (controllFilters[i] ==filtersName[j] ) {
       filterValue = form[widgetName[j]].value;
       if (filterValue == "")
	     insert=false;
	 }
   }
 }
 if (insert)
   valueList(queryName,filtersName,widgetName,targetWidgetName);
 else alert('Inserire almeno un Filtro');
}

function valueList(queryName,filtersName,widgetName,targetWidgetName,extraUrl) {
  if (waitRefresh)
    return;

  widgets = widgetName;

  url = "valueList.do?QUERYNAME="+queryName;
  for (var i = 0; i < filtersName.length; i++) {
    if (filtersName[i] != "") {
       filterValue = escape(form[widgets[i]].value);
       if (filterValue != "")
	     url += "&"+filtersName[i]+"@="+escape(form[widgets[i]].value);
	 }
  }

  if (targetWidgetName != null)
    widgets = targetWidgetName;
  
  if (extraUrl) {
	  url += "&" + extraUrl;
  }

  try{
	  sList = window.open(url, POPUP_NAME, "width=600,height=700, status = yes,resizable = yes, scrollbars = yes");
  }
  catch(err){
	  //riprovo ad aprirla con un altro nome...
	  sList = window.open(url, POPUP_NAME+new Date().getTime(), "width=600,height=700, status = yes,resizable = yes, scrollbars = yes");
  }
}

function valueListCust(contrName,queryName,filtersName,widgetName,targetWidgetName) {
  widgets = widgetName;

  url = contrName+".do?QUERYNAME="+queryName;
  for (var i = 0; i < filtersName.length; i++) {
    if (filtersName[i] != "") {
       filterValue = escape(form[widgets[i]].value);
       if (filterValue != "")
        url += "&"+filtersName[i]+"@="+escape(form[widgets[i]].value);
    }
  }

  if (targetWidgetName != null)
    widgets = targetWidgetName;

  try{
	  sList = window.open(url, POPUP_NAME, "width=420,height=450, status = yes,resizable = yes, 	scrollbars = yes");
  }
  catch(err){
	  sList = window.open(url, POPUP_NAME+new Date().getTime(), "width=420,height=450, status = yes,resizable = yes, 	scrollbars = yes");
  }
}

function lookupList(queryName,filtersName,widgetName,targetWidgetName) {
  widgets = widgetName;
  url = "valueList.do?LOOKUPNAME="+queryName;
  for (var i = 0; i < filtersName.length; i++) {
    if (filtersName[i] != "") {
       filterValue = escape(form[widgets[i]].value);
       url += "&"+escape(filtersName[i])+"@="+escape(form[widgets[i]].value);
	 }
  }

  if (targetWidgetName != null)
    widgets = targetWidgetName;

  var centerWidth = (window.screen.width - lookupWidth) / 2;
  var centerHeight = (window.screen.height - lookupHeight) / 2;
  
  try{
	  sList = window.open(url, POPUP_NAME, "width="+lookupWidth+",height="+lookupHeight+",left="+centerWidth+",top="+centerHeight+", status = yes,resizable = yes, scrollbars = yes");
  }
  catch(err){
	  sList = window.open(url, POPUP_NAME+new Date().getTime(), "width="+lookupWidth+",height="+lookupHeight+",left="+centerWidth+",top="+centerHeight+", status = yes,resizable = yes, scrollbars = yes");
  }
}

function correctWidgetNames() {
  for (var i = 0; i < widgets.length; i++) {
    wn = widgets[i];
    if (!form[widgets[i]])
      widgets[i] = wn+"@";
    if (!form[widgets[i]])
      widgets[i] = wn+"@Key";
    if (!form[widgets[i]])
      widgets[i] = wn+"@Filter";
    if (!form[widgets[i]])
      widgets[i] = wn+"@Controller";
  }
}

function lookupListController(lookupName,keyWidgets,descWidgets,widgetNames,source,data,onlyWidgetNames,filter) {
  valueListResultCallback = null;

  if (canExecLookupLC){
  form["ACTION"].value = "LOOKUP";
  widgets = widgetNames;
  correctWidgetNames();
  if(source!='null') {
	form["REQUEST_SOURCE"].value = source;
  } else
    form["REQUEST_SOURCE"].value = '';
    
  //Crea 
  //submitString = (onlyWidgetNames) ? getSubmitStringByWidgets(widgets) : getSubmitStringLookup(); 

  form["DATA"].value = lookupName+";"+keyWidgets+";"+descWidgets;
  
  if (data != null){
	form["EXTRA"].value = data;
  } else {
    form["EXTRA"].value = '';
  }
  if (filter != null) {
  	form["FILTER"].value = filter;
  } else {
    form["FILTER"].value = '';
  }
  //win1 = window.open(ss,"list", "width="+lookupWidth+",height="+lookupHeight+", status = yes,resizable = yes, scrollbars = yes");
   
    targhetOld = form.target;
    var centerWidth = (window.screen.width - lookupWidth) / 2;
    var centerHeight = (window.screen.height - lookupHeight) / 2;
    var popupName = POPUP_NAME
    try{
    	win1 = window.open('',POPUP_NAME, "width="+lookupWidth+",height="+lookupHeight+",left="+centerWidth+",top="+centerHeight+", status = yes,resizable = yes, scrollbars = yes");
    }
    catch(err){
    	popupName = POPUP_NAME+new Date().getTime();
    	win1 = window.open('',popupName, "width="+lookupWidth+",height="+lookupHeight+",left="+centerWidth+",top="+centerHeight+", status = yes,resizable = yes, scrollbars = yes");
    }
    try {
      form.target = popupName;
      form.submit();
  	  form.target = targhetOld;
    } catch(err) {
      win1.close();
    }
    
  }
}


function lookupCodeController(lookupName,keyWidgets,codeWidgets,widgetNames,source,filter) {	
  canExecLookupLC = false;
  widgets = widgetNames;
  correctWidgetNames();
  
  var data = lookupName+";"+keyWidgets+";"+codeWidgets;
  var names = new Array();
  var values = new Array();
  var j = 0; 

  if (source) {
    names[j] = 'REQUEST_SOURCE';
    values[j] = source;
    j++;
  }
  if (filter) {
    names[j] = "FILTER";
    values[j] = filter;
    j++;
  } else {
	names[j] = "FILTER";
	values[j] = "";
  }
  
  for (var i = 0; i < form.elements.length; i++) {
    if (form.elements[i].name && !form.elements[i].disabled){
      if (form.elements[i].type == "radio" || form.elements[i].type == "checkbox") {
		if (form.elements[i].checked){
	      names[j] = form.elements[i].name;
	      values[j] = form.elements[i].value;
      	}
  	  }else{
  		names[j] = form.elements[i].name;
		values[j] = form.elements[i].value;
      }
	  j++;
    }  
  }
  sendData(form.action,data,"LOOKUP.CODE",names,values);
  
}


function remLink() {
  if (window.sList && window.sList.open && !window.sList.closed)
    window.sList.opener = null;
}

function list(queryName,filtersName){
valueList(queryName,filtersName,getNameWidget());
}

function pick(symbol) {
   if(!window.opener.canExecLookupLC)
   {
		window.opener.canExecLookupLC = true;
   }
   if (window.opener && !window.opener.closed)
    window.opener.valueListResult(symbol);
   window.close();
}


//---------------------------------------------------------------------------
// Gestione lookup
// lookupName [String]      Nome del lookup
// keyWidgetName [Array]    Nomi dei widget che contengono la chiave
// targetWidgetName [Array] Nomi dei widget che riceveranno i risultati dei lookup
// fieldNames [Array]       Nomi dei campi dai visualizzare
//                          Se essere omesso mostra il primo campo

function lookup(lookupName,keyWidgetName,targetWidgetName,fieldNames) {
  var buffer = lookupName;
  var cleanTarget = false;

  //Creo la chiave
  for (var i = 0; i < keyWidgetName.length; i++) {
    value = document.forms[0][keyWidgetName[i]].value;
    if (value == "" || value == null) {
      cleanTarget = true;
      break;
    }

    buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + value;
  }
  //Widget di destinazione
  if (!cleanTarget) {
    for (var i = 0; i < targetWidgetName.length; i++)
      buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + targetWidgetName[i];

     //nome dei campi
     if (fieldNames != null)
      for (var i = 0; i < fieldNames.length; i++)
        buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + fieldNames[i];

    sendData('lookupFrame.do',buffer);
  } else {
    //Cancello i widget
    for (var i = 0; i < targetWidgetName.length; i++)
      document.forms[0][targetWidgetName[i]].value = "";
  }
}

//---------------------------------------------------------------------------
// Gestione lookup
// lookupName [String]      Nome del lookup
// keyWidgetName [Array]    Nomi dei widget che contengono la chiave
// targetWidgetName [Array] Nomi dei widget che riceveranno i risultati dei lookup
// fieldNames [Arrary]      Nomi dei campi dai visualizzare
//                          Se essere omesso mostra il primo campo

function lookupFrame(lookupName,keyWidgetName,targetWidgetName,fieldNames) {
  var buffer = lookupName;
  var cleanTarget = false;

  //Creo la chiave
  for (var i = 0; i < keyWidgetName.length; i++) {
    value = document.forms[0][widgetNameByProperty(keyWidgetName[i])].value;
    if (value == "" || value == null) {
      cleanTarget = true;
      break;
    }

    buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + value;
  }
  //Widget di destinazione
  if (!cleanTarget) {
    for (var i = 0; i < targetWidgetName.length; i++)
      buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + targetWidgetName[i];

     //nome dei campi
     if (fieldNames != null)
      for (var i = 0; i < fieldNames.length; i++)
        buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + fieldNames[i];

    sendData('lookupFrame.do',buffer);
  } else {
    //Cancello i widget
    for (var i = 0; i < targetWidgetName.length; i++)
      document.forms[0][targetWidgetName[i]].value = "";
  }
}

function lookupFrameController(lookupName,keyWidgetName,targetWidgetName,fieldNames,tunneling) {
  var buffer = lookupName;
  var cleanTarget = false;

  //Creo la chiave
  for (var i = 0; i < keyWidgetName.length; i++) {
    value = document.forms[0][widgetNameByProperty(keyWidgetName[i])].value;
    if (value == "" || value == null) {
      cleanTarget = true;
      break;
    }

    buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + value;
  }
  //Widget di destinazione
  if (!cleanTarget) {
    for (var i = 0; i < targetWidgetName.length; i++)
      buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + targetWidgetName[i];

     //nome dei campi
    if (fieldNames != null)
      for (var i = 0; i < fieldNames.length; i++)
        buffer = ((i > 0) ? (buffer + ",") : (buffer+";") ) + fieldNames[i];

		var action = "LOOKUP.FRAME";
		
		if (!tunneling) 
	    sendData(form.action,buffer,action);
		else {
			action = action + ".TUNNELING";
	    var widgetName = widgetNameByProperty(keyWidgetName[keyWidgetName.length-1]);
			var widgetNames = [widgetName];
		  var widgetValues = [form[widgetName].value];
			sendData(form.action,buffer,action,widgetNames,widgetValues);		  
    }
    
	  
  } else {
    //Cancello i widget
    for (var i = 0; i < targetWidgetName.length; i++) {
      document.forms[0][targetWidgetName[i]].value = "";
    }
    if (tunneling) {
    	propertiesChange(keyWidgetName);
    }
  }
}

function lookupControllerOnClick(propertyName, controllerName,lookupName,descWidgets,returnOnFind2) {
    if(canExecLookupLC){
      var index = controllerName+","+propertyName;
      if(descWidgets)
        descWidgets = descWidgets.replace(/=/g, '%3D');
      var extraData = "FIND2_EXTRAS="+lookupName+",("+descWidgets+")";
      if(returnOnFind2 == true || returnOnFind2 == false) {
        //presente
        extraData = extraData + ","+returnOnFind2;
      } 
      var  newDate1 =new Date();
      target = "FIND2"+newDate1.getMilliseconds();
      doActionAndIndexWindow("FIND2.CALL",index,target,"FIND2.REFRESH",null,extraData);
    }
}

function lookupEditOnClick(controllerName,keyWidgetNames,keyPropertyNames) {
    var  newDate1 =new Date();
	var link = controllerName+".do?ACTION=EDIT&"
	for (var i = 0; i < keyWidgetNames.length; i++) {
	  link += keyPropertyNames[i] + "@Key=" + form[keyWidgetNames[i]].value;
	}
	
	//alert(link);
	windowOpen(link,controllerName);
}



//---------------------------------------------------------------------------
// Gestione form note
//
var note = null;

function showNote(value) {
  note = value;
  //Marco18.03.04|tolta la cornice alla pagina 
  //open("PSGLibrary/note.jsp","Note");
	window.open("PSGLibrary/note.jsp","Note","width=400,height=350,status = yes,resizable = yes,scrollbars = yes");

}

function pickNote() {
  document.forms[0]["Note"].value = window.opener.note;
}


//-----------------------------------------------------------------------------
//  Validazione
//
//  es.: validateInput(this,['M','S5'])

function validateInput(input,options) {
  for (var i = 0; i < options.length;i ++) {
    var functionName = "validate"+options[i].charAt(0);
    var functionValue=  options[i].substr(1,options[i].length);

    var f = this[functionName];
    var result = f(input,functionValue);
    if (result != null && result != true) {
		input.select();
		//valore vuoto del campo in errore per tutti i tipi di controllo (date, numeric,interi,.....)
		if (result != null  )
			input.value="";
			
		alertBoxHeader('images/stop.png', 'Errore', result, '350', '140',"images/error_header.gif");
      //settare il fuoco sul widget errato
	  validateError = true;
      input.focus();
      return false;
    }
  }
  return true;
}

// Validazione campo [M]andatory
function validateM(input,opt) {
  val=input.value;
  if (val == null || val == "")
    return "dato richiesto";
}

// Validazione dimensioni campo SXXX dove xxx e' la dimensione
function validateS(input,opt) {
  val=input.value;
  if(val.length>eval(opt))
    return "dimensione massima:"+opt;
}

// Validazione  campo [N]umerico
function validateN(input,opt) {
  val = input.value;
  //TODO verificare presenza spazi
  if (val != null && val != "") {
    val = val.replace(/\s+/,'');
    input.value = val;
  	
    val = val.replace(/\,/,".");
    if (String(val*1)=="NaN")
      return "Atteso numero";
  }
}

// Validazione  campo [I]ntero 
function validateI(input,opt) {
  val = input.value;
  //TODO verificare presenza spazi
  if (val != null && val != "") {
    val = val.replace(/\s+/,'');
    input.value = val;
  	
    val = val.replace(/\,/,".");
    
    if (val.indexOf('.') != -1) 
  	  return "Atteso numero intero";
    if (String(val*1)=="NaN")
      return "Atteso numero intero";
    if(opt=="P"){
      if (val < 0) return "Atteso numero intero positivo";
  }
    if(opt=="Z"){
      if (val <= 0) return "Atteso numero intero maggiore di zero";
}
  }
}

// validazione data di nascita
function validateB(input,opt) {
  var result = validateD(input,"B");
  
  if (result == null) {
    var now = new Date();
    var anno=now.getYear().toString();
    var today = new Date("20"+anno.substring(anno.length-2), now.getMonth(),
        now.getDate());
    var dateString=input.value;
    var date = new Date(dateString.substring(6,10),
                              dateString.substring(3,5)-1,
                              dateString.substring(0,2));
    
    if (date > today){
     result = "Data superiore alla data odierna";
    }
  }
  
  return result;
}


// Validazione  campo [D]ata (gg/mm/aaaa - gg/mm/aa)
// Se opt=='B' e sono state indicate 2 cifre per l'anno viene aggiunto '19'
// se l'anno e' minore o uguale a quello attuale, '20' altrimenti
function validateD(input,opt) {
   return convert_date_with_no_alert(input, opt);
}

// validazione tra data DA-A

function validateDaA(inputDa,inputA,opt){
 var ret = true;
 var validateInputDaFlag = null;
 var validateInputAFlag  = null;
 //Validazione dei singoli campi secondo il formato dettato dall'option.
 if(inputDa!=undefined && inputA!=undefined){
  	if(opt=="B"){
		  validateInputDaFlag = validateB(inputDa,opt);
		  validateInputAFlag = validateB(inputA,opt);
	  }else{
	 		if(opt=="I"){
		  	validateInputDaFlag = validateI(inputDa,opt);
		  	validateInputAFlag = validateI(inputA,opt);
	 		}else{
	  		if(opt=="N"){
		  		validateInputDaFlag = validateN(inputDa,opt);
		  		validateInputAFlag = validateN(inputA,opt);
	 			}else{
	 			  validateInputDaFlag = validateD(inputDa,opt);
	 				validateInputAFlag = validateD(inputA,opt);
	 			}
	 		}
	 }
	 //Se fallisce la prima parte di validazione, ritorna false;
	 if(validateInputDaFlag != null){
		    alert(validateInputDaFlag);
	 		return false;
	 }
	 if(validateInputAFlag != null){
		    alert(validateInputAFlag);
	 		return false;
	 }
	
	 //Validazione DA -  A secondo il formato dettato dall'option.
	 if(inputDa.value!=null && inputA.value!=null && inputDa.value!="" && inputA.value!=""){
		 var dateStringDa=inputDa.value;
  	 var dateStringA=inputA.value;
		 if (opt == "I" || opt == "N") {
 		   if (dateStringDa > dateStringA){
		     alert('Sono stati indicati numeri "da" - "a" non corretti');
		     ret = false;
		   }
	   }
	   else {
		 var dateDa = new Date(dateStringDa.substring(6,10),
		                            dateStringDa.substring(3,5)-1,
		                            dateStringDa.substring(0,2));
		 var dateA = new Date(dateStringA.substring(6,10),
		                            dateStringA.substring(3,5)-1,
		                            dateStringA.substring(0,2));
		  if (dateDa > dateA){
		   alert('La data "da" deve essere antecedente alla data "a"');
		   ret = false;
		  }
		 }
	 }
 }
  return ret;
}
// Validazione  campo [T]ime (oo:mm)
function validateT(input,opt) {
	var time = input.value;
	if(time == null || time == '')
		return null;
	
	var ret = false;	
		 
   if (time.match('^([0-1][0-9]|2[0-3])(:|,|.|)([0-5][0-9])$')) {
   			time = time.replace(".",":");
   		  time = time.replace(",",":");
   		  time = time.replace(" ",":");
   		 if(time.length == 4)
  			time = time.substr(0,2) + ":" + time.substr(2,4);		
  			
   			input.value = time;
      	ret = true;
 		} else {
      ret = 'Attesa Ora HH:MM';
 		}
 	return ret;
}



//---------------------------------------------------------------------------
// Gestione Errori
//

function writeError(e,tipo) {
   if (tipo == null) {
     document.write("<input type='BUTTON' CLASS='BTN' NAME='Errore' VALUE='!'>");
   } else if (tipo == "GLOBAL") {
     document.write("<FIELDSET><LEGEND class='fieldset_error'>ERRORE!</LEGEND>"+e+"</FIELDSET>");
   }
}


//Uppercase
//<input type=text name=pctext onchange="forceuppercase(this);">
function forceuppercase(textbox){
     var string = textbox.value;
     textbox.value = string.toUpperCase();
}

//-----------------------------------------------------------
// gestione apertura pagine

function openLink(href,thisWindow,target) {
 if (thisWindow=='N')
   window.open(href,target,'width=791,height=524,screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=no,menubar=no,scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes');
 else
   window.document.location.href=href;
}

function openLinkFS(href,target) {
  w = screen.availWidth-10;
  h = screen.availHeight-143;
  features = "width="+w+",height="+h;
  features += ",left=0,top=0,screenX=0,screenY=0,left=0,top=0,resizable=yes,toolbar=yes,menubar=yes,location=yes,scrollbars=yes,titlebar=yes,alwaysRaised=yes,status=yes";

  window.open(href,target,features);
}


// Crea una stringa per effettuare un submit tramite open
function getSubmitString() {
    result = form.action;
    for (var i = 0; i < form.elements.length; i++) {
      if (i == 0)
        result += "?";
      if (i > 0)
        result += "&";
        
      var element = form.elements[i];  
      var objectType = element.type;
        
      if (objectType != "button") { 
      	  if (objectType == "radio" || objectType == "checkbox") {
	      	if (element.checked)
	          result += escape(element.name)+"="+escape(element.value);
	      } else {
	        result += escape(element.name)+"="+escape(element.value);
	      }
      } 
    }
    return result;
}

function extraDataToArrays(extraData, result) {
	var ret = result;
	var start; 
	if (!result) {
		ret = new Array();
		ret[0] = new Array();
		ret[1] = new Array();
		start = 0;
	} else {
		start = ret[0].length;
	}
	var spl = extraData.split('&');
    for (var i = 0; i < spl.length; i++) {
    	var s = spl[i].split('=');
		ret[0][start+i] = s[0];    	
		ret[1][start+i] = s[1];    	
	}
	return ret;
}

// Crea un array di array per effettuare un submit tramite open
function getSubmitArrays() {
	var result = new Array();
	result[0] = new Array();
	result[1] = new Array();
	
    for (var i = 0; i < form.elements.length; i++) {
      var element = form.elements[i];  
      var objectType = element.type;
      if (objectType != "button") { 
      	  if (objectType == "radio" || objectType == "checkbox") {
	      	if (element.checked)
	      	{
	          result[0][i] = element.name;
	          result[1][i] = element.value;
	      	}
	      } else {
            result[0][i] = element.name;
            result[1][i] = element.value;
	      }
      } 
    }
    return result;
}

// Crea una stringa per effettuare un submit tramite open per i lookup
function getSubmitStringLookup() {
    result = form.action;
    for (var i = 0; i < form.elements.length; i++) {
      if (i == 0)
        result += "?";
      if (i > 0)
        result += "&";
        
      var element = form.elements[i];  
      var objectType = element.type;
      
      if (objectType != "textarea" && objectType != "button") {        
		if (objectType == "radio" || objectType == "checkbox") {
			if (element.checked)
				result += escape(element.name)+"="+escape(element.value);
		} else {
			result += escape(element.name)+"="+escape(element.value);
		}  
      }
    }
    return result;
}

// Crea una stringa per effettuare un submit prendendo i dati dai widgets specificati
function getSubmitStringByWidgets(widgets) {
	widgetNames = widgets.concat('ACTION',widgets);
    result = form.action;
    for (var i = 0; i < widgetNames.length; i++) {
      if (i == 0)
        result += "?";
      if (i > 0)
        result += "&";
        
      var element = form[widgetNames[i]];  
      if (element) {
	      var objectType = element.type;
	      
	 	    if (objectType == "radio" || objectType == "checkbox") {
			    if (element.checked)
				    result += escape(element.name)+"="+escape(element.value);
	  	  } else {
			    result += escape(element.name)+"="+escape(element.value);
		    }  
      }	
    }
    return result;
}


function setFocusWidget(widgetName) {
  if (widgetName && (typeof widgetName) != "string") {
    widgetName = null;
  }
  if (widgetName) {
    if (form[widgetName]) {
      var widget = form[widgetName];
      if (!widget.disabled && widget.focus && widget.type.toUpperCase() != 'HIDDEN' )
        widget.focus();
    } else if (widgetName.substring(0,1) == '#') {
      window.document.location.href = widgetName;   
    }
  }
}

// Controllo dei campi obbligatori
function controlFields() {
    result = true;
    for (var i = 0; i < form.elements.length; i++) {
	 var elem = form.elements[i];	
	 
	 var err=false;
	 if(elem.className && elem.className.indexOf("mandatoryField")!=-1 && elem.value == "")
		 err=true;
	 if(elem.className && elem.className.indexOf("mandatoryField")!=-1 && elem.type == "radio")
		 err=!checkRadioFields(elem.name);
	 if(!isWindowsCE){
		 //aggiunto controllo per le multiSelect
		 if($(elem).hasClass('multiSelect') && $(elem).hasClass('mandatoryField'))
			 err=!$(elem).hasMultiSelectOptionsSelected($(elem));
	 }
	 
	 if(err){
		//Marco 05.03.04 | ripristina lo stato del cursore, da clessidra a freccia
           if(!isWindowsCE){
             setCursor('auto');
           }
           if (elem.getAttribute('Caption') != null){
           	 alert('INSERIRE I CAMPI OBBLIGATORI: ' + elem.getAttribute('Caption'));
           } else {
           	 alert('INSERIRE I CAMPI OBBLIGATORI');
           }
    	    if(!elem.disabled && elem.focus && elem.type.toUpperCase() != 'HIDDEN')
           	 elem.focus();
           result = false;
           break;
        }
    }
    
    if(!customControlFields())
    	result= false;

    return result;
}

function customControlFields(){
	return true;
}

//Tk 466961 Aggiunto controllo per radio button obbligatori.
function checkRadioFields(radioName){
	var result=false;
	var radios=document.getElementsByName(radioName);
	for(var i=0; i<radios.length;i++)
		result= result || radios[i].checked;						
	return result;
}

// FIXME Sembra che non funzioni!
function widgetNameByProperty(propertyName,source) {
  if (source == null) {
    if (form[propertyName])
      return propertyName;
    if (form[propertyName+"@"])
      return propertyName+"@";
    if (form[propertyName+"@Key"])
      return propertyName+"@Key";
    if (form[propertyName+"@Controller"])
      return propertyName+"@Controller";
    if (form[propertyName+"@Filter"])
      return propertyName+"@Filter";
  } else {
    if (form[propertyName])
      return propertyName;
    if (source == "mainObject" || source == "") {
      if (form[propertyName+"@Key"])
        return propertyName+"@Key";
      return propertyName+"@";
    }
    else if (source == "filter" || source ==  "findFilter") 
      return propertyName+"@Filter";
    else if (source == "controller") 
      return propertyName+"@Controller";
  }
}




//-------------------------------------------------------------
// set del variabili JSP

function varibiliValori(variabili, value){
 var variabili;
 var value;
 for (var i = 0; i < variabili.length; i++)
      form[variabili[i]].value = value[i];
  doRefresh();
}

function selDesel(prefix,checkBox) {
	for (var i = 0; i < form.elements.length; i++) {
	  var element = form.elements[i];  
	  if (element.name && element.name.indexOf(prefix) == 0) {
	    element.checked = checkBox.checked;
	  } 
	}
}

//Ritorna il valore associato ad un widget identificato tramite nome
function getWidgetValueByName(widgetName) {
    //Carico il valore direttamente
    var elements= document.getElementsByName(widgetName);

    var result = [elements[0].value];


    for (var i=0; i<elements.length; i++) {
        if (elements[i].type == "radio") {
            if (elements[i].checked) {
                result = [elements[i].value];
                break;
            }
        } else if (elements[i].type == "checkbox") {
            if (elements[i].checked) {
                result = [elements[i].value];
                break;
            } else {
                result = [elements[i].getAttribute("UNCHECKEDVALUE")];
                break;
            }
        }
    }
    return result;

} 


function propertyChange(widgetName) {
	var widgetNames = [widgetName];
  var widgetValues = getWidgetValueByName(widgetName);
  sendData(form.action,'','PROPERTY_CHANGE.SINGLE',widgetNames,widgetValues);
}

function propertiesChange(widgetNames) {
  var widgetValues = [];
  for (var i = 0; i < widgetNames.length; i++) {
    widgetValues[i] = form[widgetNames[i]].value;
  }
  sendData(form.action,'','PROPERTY_CHANGE.SINGLE',widgetNames,widgetValues);
}

//------------------------------------------------------------
// tipo di browser w versione

function typeBrowser(tipo,versione){
 var tipo;
 var versione;
 browser = (((navigator.appName == tipo) &&
(parseInt(navigator.appVersion) >= versione ))
	      || ((navigator.appName == tipo) &&
(parseInt(navigator.appVersion) >= versione )));
    if (browser) {return true;}
	else {return false;}
}

//

//Funzione fittizia per evitare la validazione automatica da lista valori
function noListValidate() {
}

//------------------------------------------------------------

//Funzioni per controllo input campi data
function checkdate(objName) {
	var datefield = objName;
	if (chkdate(objName) == false) {
		datefield.select();
		alert("La data non e' corretta!");
		datefield.focus();
		return false;
	}
	else {
		return true;
   }
}

function chkdate(objName) {
	//var strDatestyle = "US"; //United States date style
	var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield.value;
	if (strDate.length < 1) {
		return true;
	}
	for (var intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}
			else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}
	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
	}
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	// US style
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (var i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
		   }
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
	   }
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		}
		else {
			if (intday > 28) {
				err = 10;
				return false;
			}
		}
	}
	
//	if (strDatestyle == "US") {
//		datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
//	}
//	else {
//		datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
//	}
	return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { 
			return true; 
		}
	} 
	else {
		if ((intYear % 4) == 0) {
			return true; 
		}
	}
	return false;
}

function doDateCheck(from, to) {
	if (Date.parse(from.value) <= Date.parse(to.value)) {
		alert("Le date non sono corrette!");
	}
	else {
		if (from.value == "" || to.value == "") 
			alert("Inserire entrambe le date!");
		else 
			alert("La data di arrivo e' inferiore alla data di partenza!");
   }
}

//------------------------------------------------------------
// Esempio : <textarea name=message1 wrap=physical cols=28 rows=4 onKeyDown="textCounter(this,125);" onKeyUp="textCounter(this,125);"></textarea>
function textCounter(field,maxlimit,countfield) {
  if (field.value.length > maxlimit)
    field.value = field.value.substring(0, maxlimit);
  else 
    if (countfield)
       countfield.value = maxlimit - field.value.length;
}

//--------------------------------------------------------------------------
//gestione tooltip

function Popup( left, top, height, width ) {
  this.left = left;
	this.top = top;
	this.height = height;
	this.width = width;
	this.visible = false;
	/*
	 * Commentato per far s� che il tooltip si ridimensioni anche su IE
	 * 
	if( document.all ) {
		isIE = true;
	} else {
		isIE = false;
	}
	if( isIE ) { // Internet Explorer Popup
		this.popupObj = window.createPopup();
		this.popupObj.document.createStyleSheet(css); 
		this.popupObj.document.body.style.margin="0px";
		this.setContent = function( text ) {
			this.popupObj.document.body.innerHTML = text;
		}
		this.show = function() {
			this.popupObj.show( this.left, this.top, this.width, this.height, document.body );
			this.visible = true;
		}
		this.hide = function() {
			this.popupObj.hide();
			this.visible = false;
		}
		this.setBgColor = function( color ) {
            this.popupObj.document.body.style.backgroundColor = color;
        }
	} else { // Mozilla/Netscape Popup
	*/
		this.popupObj = document.createElement( "div" );
		// Random ID
		rnd = Math.ceil( ( ( (new Date()).getTime() * 9301 + 49297 ) % 233280 ) / 233280 * 100000000 );
		this.popupObj.id = "POPUP" + rnd;
		this.popupObj.style.visibility = "hidden";
		this.popupObj.style.position = "absolute";
		this.popupObj.style.backgroundColor = "white";
		document.body.appendChild( this.popupObj );
		this.setContent = function( text ) {
			this.popupObj.innerHTML = text;	
		}
		this.setBgColor = function( color ){
		 this.popupObj.style.backgroundColor =color;
		}	
		
		this.show = function() {
		  this.popupObj.style.zIndex = 1000;
                     this.popupObj.style.top = this.top + document.body.scrollTop - 1;
                     this.popupObj.style.left = this.left + document.body.scrollLeft - 1;
			this.popupObj.style.height = this.height;
			this.popupObj.style.width = this.width;
			this.popupObj.style.visibility = "visible";
			this.visible = true;
		}	
		this.hide = function() {
		  this.popupObj.style.zIndex = -1;
			this.popupObj.style.visibility = "hidden";
			this.visible = false;
			$(this.popupObj).remove();
		}

//	}
	this.move = function( top, left ) {
		wasVisible = this.visible;
		if( wasVisible ) this.hide();
		this.top = top;
		this.left = left;
		if( wasVisible ) this.show();
	}
	this.resize = function( height, width ) {
		wasVisible = this.visible;
		if( wasVisible ) this.hide();
		this.height = height;
		this.width = width;
		if( wasVisible ) this.show();
	}
}

function strtrim() {
	//Match spaces and nbsp; at beginning and end of text and replace
	//with null strings
	return this.replace(/^\s+/,'').replace(/\s+$/,'').replace(/^\xa0/,'').replace(/\xa0/,'');
}
String.prototype.trim = strtrim;
 
 var popupWindow;
 function showPopupTip(text, left, top, height, width, bgColor) {
    popupWindow = new Popup(left, top, height, width);
    popupWindow.setContent(unescape(text));
    popupWindow.setBgColor(bgColor)
    popupWindow.show();
 }
 function showCSSToolTip(text, left, top, height, width) {
	text = "<table class=%22tooltip%22><tr><td>"+text+"</td></tr></table>";
	hidePopup(); 
    popupWindow = new Popup(left, top, height, width);
    popupWindow.setContent(unescape(text));
    popupWindow.show();
 }
 
 function showCSSToolTip2(e,text, left, top, height, width) {
 	var type = "";
 	var str = "";
 	var x = e.clientX+10;
 	var y = e.clientY+10;
 	var h = 25;
 	var w = 100;
 	if (left) {
 		if (left>=0) x = left;
 	}
 	if (top) {
 		if (top>=0) y = top;
 	}
 	if (height) {
 		h = height;
 	}
 	if (width) {
 		w = width;
 	}
 	if (is_ie) {
	 	type = e.srcElement.name;
	 	str = e.srcElement.value ? e.srcElement.value.trim() : "";
	} else {
	 	type = e.target.name;
	 	str = e.target.value ? e.target.value.trim() : "";
	}
	if (text) {
		str = text;
	}
	
	if (type == "BTN_INSERT") {
		showCSSToolTip('F3 - '+str,x,y,h,w);
	} else if (type == "BTN_CONFIRM") {
		showCSSToolTip('F4 - '+str,x,y,h,w);
	} else if (type == "BTN_DELETE") {
		showCSSToolTip('F5 - '+str,x,y,h,w);
	} else if (type == "BTN_STAMPA") {
		showCSSToolTip('F6 - '+str,x,y,h,w);
	} else if (type == "BTN_ANTEPRIMA") {
		showCSSToolTip('F7 - '+str,x,y,h,w);
	} else if (type == "BTN_CANCEL") {
		showCSSToolTip('F8 - '+str,x,y,h,w);
	} else if (type == "BTN_EXIT") {
		showCSSToolTip('Esc - '+str,x,y,h,w);
	} else {
		showCSSToolTip(str,x,y,h,w);
	}
 }
 
 function showCSSToolTip3(e,text, left, top, height, width) {
   if(!text)
     return;
   var x = e.clientX+10;
   var y = e.clientY+10;
   var h = 25;
   var w = 100;

   if (height) {
     h = height;
   }
   if (width) {
     w = width;
     x = e.clientX-(width/2)+10;
     if (x<0) x=0;
   }

   if (left) {
     if (left>=0) x = left;
   }
   if (top) {
     if (top>=0) y = top;
   }

   showCSSToolTip(text,x,y,h,w);

 }

 function hidePopup() {
 	if (popupWindow)
	    popupWindow.hide();    
 }

//-------------------------------------------------------------
//   Gestione Help
//-------------------------------------------------------------
var helpStatic = false;
function doHelp(customLink) {
  var link;
  
  if (customLink)
    link = customLink;
  else
    link = helpLink;  
    
  if(!helpStatic) {
  	var act = 'HELP' + ((link) ? ('&LINK='+ escape(link)) : '');
	doActionWindow(act);
  } else	
	hw = window.open(link); 
} 


//-------------------------------------------------------------
//   Gestione Debugger
//-------------------------------------------------------------
function doDebug() {
  doActionWindow("SCRIPT.EDITOR_OPEN","scriptEditor") 
} 



//-------------------------------------------------------------
//   Mostra gli errori
//-------------------------------------------------------------
var haveErrors = false;

function showGlobalError(error) {
	if (!haveErrors) {
		haveErrors = true;
		alert('Sono presenti degli errori');
	}
	document.write('<center><table class="errorBox"><tr><td>'+error+'</td></tr></table><center>');
}

function showError(error) {
	if (!haveErrors) {
		haveErrors = true;
		alert('Sono presenti degli errori');
	}
	//document.write('<span class="fieldset_error">'+error+'</span>');
}


//-------------------------------------------------------------
//   Gestione Cookie
//-------------------------------------------------------------

function getCookieVal (offset) {  
var endstr = document.cookie.indexOf (";", offset);  
if (endstr == -1)    
endstr = document.cookie.length;  
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {  
  var arg = name + "=";  
  var alen = arg.length;  
  var clen = document.cookie.length;  
  var i = 0;  
  while (i < clen) {    
    var j = i + alen;    
    if (document.cookie.substring(i, j) == arg)      
      return getCookieVal (j);    
    i = document.cookie.indexOf(" ", i) + 1;    
    if (i == 0) 
      break;   
  }  
  return null;
}

function SetCookie (name, value) {  
  var argv = SetCookie.arguments;  
  var argc = SetCookie.arguments.length;  
  var expires = (argc > 2) ? argv[2] : null;  
  var path = (argc > 3) ? argv[3] : null;  
  var domain = (argc > 4) ? argv[4] : null;  
  var secure = (argc > 5) ? argv[5] : false;  
  document.cookie = name + "=" + escape (value) + 
                    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
                    ((path == null) ? "" : ("; path=" + path)) +  
                    ((domain == null) ? "" : ("; domain=" + domain)) +    
                    ((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {  
  var exp = new Date();  
  exp.setTime (exp.getTime() - 1);  
  var cval = GetCookie (name);  
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}



// ----------- Calendar ---------------------------


 function calendarDate(data) {
  var wid=document.forms[0][data];
  if(wid.value !=""){
  	 var dt = wid.value.replace("-", "/").split("/");
     return new Date(dt[1]+'/'+dt[0]+'/'+dt[2]);
	 } else return new Date();  
	}

 function normalizzaControllerName(controllerName) {
  out = "\."; // replace this
  add = "_"; // with this
  temp = "" + controllerName; // temporary holder
  
  while (temp.indexOf(out)>-1) {
   pos= temp.indexOf(out);
   temp = "" + (temp.substring(0, pos) + add + 
   temp.substring((pos + out.length), temp.length));
  }
  return temp;
 }


// ------------------ Find3 ---------------------------------
function checkAll(prefix,checked) {
    for (var i = 0; i < form.elements.length; i++) {
      var element = form.elements[i];
      if (element.type == "checkbox" && (element.name.indexOf(prefix) == 0 || prefix == "FIND3.")){
      		if(element.checked != checked && !element.disabled){
		      	element.checked = checked;
	       		if (element.onclick)
	       			element.onclick();
       		}
      } 
    }
}

// ----------------- Calcolo offset di un oggetto ----------------
// il verso � una stringa "X" per il calcolo dell'ascissa e "Y" per l'ordinata
function offsetCalc(obj,verso) {
  var offset = 0;
  while (obj != null) {
    offset += (verso=="X")?obj.offsetLeft:obj.offsetTop;
    obj = obj.offsetParent;
  }
  return offset;
}


// ----------------- Visualizza la riga elemenIndex nella tabella in containerName ----------------
function detailPositionRow(containerName, elementIndex) {
  var firstButton = -1;
  var positionTop = -1;
  
  //Cerco tutti pulsanti all'intero del div
  $("."+containerName+" button").each(function(i) {
    //Verifico che lo script sia quello di selezione
    var clickfunction = this.onclick.toString();
    var selectIdx = clickfunction.indexOf('SELECT');
    //Prendo l'indice della SELECT
    if (selectIdx > 0) {
    
      if (firstButton == -1)
        firstButton = offsetCalc(this,"Y");
    
      var strIndex = /\d+/.exec(clickfunction); 
      if (strIndex == elementIndex) {
        //Porto come primo elemento
        positionTop = offsetCalc(this,"Y") - firstButton; 
      }
    }
    
  });
  
  $("."+containerName).each(function(i) {
    this.scrollTop = positionTop;
  });
}
   




//------------------------- funzioni Custom ------------------------------------
//-- Se necessario vanno reimplementate nei vari controller,                  --
//-- devono tornare true se intercettano l'azione                             --

function customLookupOnClick(propertyName) {
  return false;
}

function customLookupCode(propertyName) {
  return false;
}

function customLookupEdit(propertyName) {
}


function customLookupOnChange(propertyName,tunneling) {
  return false;
}


//function customOnLoad() {
//}

function moveMenuButtons() {
}



//********************FUNZIONI AGGIUNTE VALIDAZIONE/FORMATTAZIONE DATE PER MERGE CON FICommons.js**********************************

function convert_date(field1, opt) {
  var ret = convert_date_with_no_alert(field1, opt);
  if (ret != null) {
    field1.select();
    alert(ret);
    //settare il fuoco sul widget errato
    field1.focus();
  }
  return ret;
}

function convert_date_with_no_alert(field1, opt) {
	var fLength = field1.value.length; // Length of supplied field in characters.
	var divider_values = new Array ('-','.','/',' ',':','_',','); // Array to hold permitted date seperators.  Add in '\' value
	var array_elements = 7; // Number of elements in the array - divider_values.
	var day1 = new String(null); // day value holder
	var month1 = new String(null); // month value holder
	var year1 = new String(null); // year value holder
	var divider1 = null; // divider holder
	var outdate1 = null; // formatted date to send back to calling field holder
	var counter1 = 0; // counter for divider looping
	var divider_holder = new Array ('0','0','0'); // array to hold positions of dividers in dates
	var s = String(field1.value); // supplied date value variable
	
	//If field is empty do nothing
	if ( fLength == 0 ) {
	   return null;
	}
	
	// Deal with today or now
	if ( field1.value.toUpperCase() == 'NOW' || field1.value.toUpperCase() == 'TODAY' ) {
	
		var newDate1 = new Date();
	
	  		if (navigator.appName == "Netscape") {
	    		var myYear1 = newDate1.getYear() + 1900;
	  		}
	  		else {
	  			var myYear1 =newDate1.getYear();
	  		}
	
		var myMonth1 = newDate1.getMonth()+1;
		var myDay1 = newDate1.getDate();
		field1.value = myDay1 + "/" + myMonth1 + "/" + myYear1;
		fLength = field1.value.length;//re-evaluate string length.
		s = String(field1.value);//re-evaluate the string value.
	}
	
	//Check the date is the required length
	if ( fLength != 0 && (fLength < 6 || fLength > 11) ) {
		return invalid_date_with_no_alert(field1);
	}
	
	// Find position and type of divider in the date
	for ( var i=0; i<3; i++ ) {
		for ( var x=0; x<array_elements; x++ ) {
			if ( s.indexOf(divider_values[x], counter1) != -1 ) {
				divider1 = divider_values[x];
				divider_holder[i] = s.indexOf(divider_values[x], counter1);
				counter1 = divider_holder[i] + 1;
				break;
			}
	 	}
	 }
	
	// if element 2 is not 0 then more than 2 dividers have been found so date is invalid.
	if ( divider_holder[2] != 0 ) {
      return invalid_date_with_no_alert(field1);
	}
	
	// See if no dividers are present in the date string.
	if ( divider_holder[0] == 0 && divider_holder[1] == 0 ) {
	
			//continue processing
			if ( fLength == 6 ) {//ddmmyy
	   		day1 = field1.value.substring(0,2);
	     		month1 = field1.value.substring(2,4);
	  			year1 = field1.value.substring(4,6);
	  			if ( (year1 = validate_year(year1, opt)) == false ) {
                  return invalid_date_with_no_alert(field1);
					}
				}
	
			else if ( fLength == 7 ) {//ddmmmy
	   		day1 = field1.value.substring(0,2);
	  			month1 = field1.value.substring(2,5);
	  			year1 = field1.value.substring(5,7);
	  			if ( (month1 = convert_month(month1)) == false ) {
                  return invalid_date_with_no_alert(field1);
					}
	  			if ( (year1 = validate_year(year1, opt)) == false ) {
                  return invalid_date_with_no_alert(field1);
					}
				}
			else if ( fLength == 8 ) {//ddmmyyyy
	   		day1 = field1.value.substring(0,2);
	  			month1 = field1.value.substring(2,4);
	  			year1 = field1.value.substring(4,8);
				}
			else if ( fLength == 9 ) {//ddmmmyyyy
	   		day1 = field1.value.substring(0,2);
	  			month1 = field1.value.substring(2,5);
	  			year1 = field1.value.substring(5,9);
	  			if ( (month1 = convert_month(month1)) == false ) {
                  return invalid_date_with_no_alert(field1);
					}
				}
	
			if ( (outdate1 = validate_date(day1,month1,year1)) == false ) {
			//	"Please enter a valid date in the format dd/mm/yyyy");
	
	
			return  "Inserire una data valida nel formato gg/mm/aaaa!";
				}
	
			field1.value = outdate1;
			return null;// All OK
			}
	
	// 2 dividers are present so continue to process
	if ( divider_holder[0] != 0 && divider_holder[1] != 0 ) {
	  	day1 = field1.value.substring(0, divider_holder[0]);
	  	month1 = field1.value.substring(divider_holder[0] + 1, divider_holder[1]);
	  	year1 = field1.value.substring(divider_holder[1] + 1, field1.value.length);
		}
	
	if ( isNaN(day1) && isNaN(year1) ) { // Check day and year are numeric
      return invalid_date_with_no_alert(field1);
	   }
	
	if ( day1.length == 1 ) { //Make d day dd
	   day1 = '0' + day1;
	}
	
	if ( month1.length == 1 ) {//Make m month mm
		month1 = '0' + month1;
	}
	
	if ( year1.length == 2 ) {//Make yy year yyyy
	   if ( (year1 = validate_year(year1, opt)) == false ) {
         return invalid_date_with_no_alert(field1);
			}
	}
	
	if ( month1.length == 3 || month1.length == 4 ) {//Make mmm month mm
	   if ( (month1 = convert_month(month1)) == false) {
        return invalid_date_with_no_alert(field1);
	   }
	}
	
	// Date components are OK
	if ( (day1.length == 2 || month1.length == 2 || year1.length == 4) == false) {
       return invalid_date_with_no_alert(field1);
	}
	
	//Validate the date
	if ( (outdate1 = validate_date(day1, month1, year1)) == false ) {
		//"Please enter a valid date in the format dd/mm/yyyy");
		return "Inserire una data valida nel formato gg/mm/aaaa!";
	}
	
	// Redisplay the date in dd/mm/yyyy format
	field1.value = outdate1;
	return null;//All is well
	
}





function convert_month(monthIn) {

var month_values = new Array ("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");

monthIn = monthIn.toUpperCase();

if ( monthIn.length == 3 ) {
	for ( var i=0; i<12; i++ )
		{
   	if ( monthIn == month_values[i] )
   		{
			monthIn = i + 1;
			if ( i != 10 && i != 11 && i != 12 )
				{
   			monthIn = '0' + monthIn;
				}
			return monthIn;
			}
		}
	}

else if ( monthIn.length == 4 && monthIn == 'SEPT') {
   monthIn = '09';
   return monthIn;
	}

else {
	return false;
	}
}

function invalid_date(inField) {
  alert(invalid_date_with_no_alert(inField));
  inField.focus();
  inField.select();
  return true;
}

function invalid_date_with_no_alert(inField)
{
  return "Inserire una data valida nel formato gg/mm/aaaa!";
}

/******************************************************************
   validate_date()

   Validates date output from convert_date().  Checks
   day is valid for month, leap years, month !> 12,.


*******************************************************************/
function validate_date(day2, month2, year2)
{
var DayArray = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var MonthArray = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
var inpDate = day2 + month2 + year2;
var filter=/^[0-9]{2}[0-9]{2}[0-9]{4}$/;

//Check ddmmyyyy date supplied
if (! filter.test(inpDate))
  {
  return false;
  }
/* Check Valid Month */
filter=/01|02|03|04|05|06|07|08|09|10|11|12/ ;
if (! filter.test(month2))
  {
  return false;
  }
/* Check For Leap Year */
var N = Number(year2);
if ( ( N%4==0 && N%100 !=0 ) || ( N%400==0 ) )
  	{
   DayArray[1]=29;
  	}
/* Check for valid days for month */
for(var ctr=0; ctr<=11; ctr++)
  	{
   if (MonthArray[ctr]==month2)
   	{
      if (day2<= DayArray[ctr] && day2 >0 )
        {
        inpDate = day2 + '/' + month2 + '/' + year2;
        return inpDate;
        }
      else
        {
        return false;
        }
   	}
   }
}


function validate_year(inYear, opt)
{
  if(inYear >= 0)
  {
	  if(opt=="B")
	  {
	  	var now = new Date();
	    var anno=now.getYear().toString();
	    if(inYear>anno.substring(anno.length-2))
	         return "19" + inYear;
	  }
	  inYear = "20" + inYear;
	  return inYear;
	}
	else
		return false;
}


//***************************************************************************************************



///*********************************utilizzate unicamente nelle jsp AziendaOspedalieraEdit, ComuniFind, ComuniEdit*****************************************************************************//


function disabilitaInputs(mydiv, disabilita, clear) {
	// mydiv:Object = l'oggetto DIV
	// diabilita: boolean = abilita/disabilita
	// clear:boolean = svuota i values
	var theInputs = mydiv.getElementsByTagName("INPUT");
	var i;
	for (i=0; i<theInputs.length; i++) {
        if (clear && (theInputs[i].type !='button')) {
	   		theInputs[i].value = '';
        }
        if (clear&&(theInputs[i].type =='radio')){ 
        //se radio button, tolgo il checked
			if (theInputs[i].checked) {
				theInputs[i].checked = false;
			}
        }
        if (clear&&(theInputs[i].type =='checkbox')){ 
        //se checkbox, tolgo il checked
			if (theInputs[i].checked){
				theInputs[i].checked = false;
			}
        }
        if ((theInputs[i].type !='button')&&(theInputs[i].type !='checkbox')&&(theInputs[i].type !='radio')){
        	setClass(theInputs[i],disabilita?"lockedField":"form_01");
			theInputs[i].readonly = disabilita;
        }
		theInputs[i].disabled = disabilita;
	}

	var theTextareas = mydiv.getElementsByTagName("TEXTAREA");
	for (i=0;i<theTextareas.length;i++){
		if (clear)
			theTextareas[i].value = '';
       	setClass(theTextareas[i],disabilita?"lockedField":"form_01");
		theTextareas[i].disabled = disabilita;
		theTextareas[i].readonly = disabilita;
	}

	var theCombos = mydiv.getElementsByTagName("SELECT");
	for (i=0;i<theCombos.length;i++){
		if (clear &&(theCombos[i].type !='select'))
			theCombos[i].value = '';
       	setClass(theCombos[i],disabilita?"lockedField":"form_01");
		theCombos[i].disabled = disabilita;
	}
	var theButtons = mydiv.getElementsByTagName("BUTTON");
	for (i=0;i<theButtons.length;i++){
		// lockButton() in psgcommon.js
    	lockButton(theButtons[i],disabilita);
	}
}



function setDisableByGroupId(divId,clear)
/*      can be used to disable and set the form elements in a div tag
	Example of call -- "javascript:parent.top.jsFrame.setMsgByAlert(div_id,'Y')"
        groupId := valore accomunante ID
        clear := 'Y' -> si effettua pulizia
*/
{
	var mydiv=document.getElementById(divId);
	disabilitaInputs(mydiv,true,clear=='Y');
}

function setEnableByGroupId(divId,clear)
/*      can be used to enable and set the form elements in a div tag
	Example of call -- "javascript:parent.top.jsFrame.setMsgByAlert(div_id,'Y')"
        groupId := valore accomunante ID
        clear := 'Y' -> si effettua pulizia
*/
{
	var mydiv=document.getElementById(divId);
	disabilitaInputs(mydiv,false,clear=='Y');
}
/* Permette di effettuare una validazione sul tipo del dato prima
	di chiamare il propertyChange.
	Es.: propertyChangeAndValidate(this,['M','S5'])
*/
function propertyChangeAndValidate(widget,options){
	if( validateInput(widget,options) ){
	  propertyChange(widget.name);
	}
}

function sfoglia(editBox) {
	sfogliaWin = window.open("","","width=450,height=10,screenX=200,screenY=170,left=200,top=170,resizable=no,toolbar=no,menubar=no,scrollbars=no,titlebar=no,status=no");
	sfogliaWin.document.writeln('<html><head><title>Sfoglia</title></head>');	
	sfogliaWin.document.writeln('<BODY><br>');
	sfogliaWin.document.write('<input type="file" size="50" onChange="window.opener.document.forms[0].elements[');
	sfogliaWin.document.write("'"+editBox+"'].value=");
	sfogliaWin.document.writeln('this.value;window.close()">');
	sfogliaWin.document.writeln('</body></html>');
}

/*
 * Permette di cambiare tutti i punti del valore del widget in virgola
 * Serve nela caso in cui uno inserisca un numero col tastierino numerico e immetta un punto per
 * definire i decimali (Oracle non vuole che ci sia un punto che divida i decimali) 
 * - sggiunta modifica per inserimento erroneo di punti per le migliaia
 */
function changePoint2Comma(input) {
	val = input.value;
    if (val != null && val != ""){
         var pos = val.indexOf(',');
         var  posFinale = val.length;
         var firstPart=val.substring(0, pos);
         var secondPart = val.substring(pos, posFinale);
          if(secondPart.search(/,/) != -1){
            var firstPartReplaced=firstPart.replace(".", "");
            var secondPartReplaced=secondPart.replace(".", ",");
            var total=firstPartReplaced.concat(secondPartReplaced);
            total = total.replace(/\s+/,'');
            input.value=total;
           }else{
            val = val.replace(/\s+/,'');
            val = val.replace(/\./,",");
            input.value = val;
     }
   } 
}

// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006 www.cryer.co.uk
function includeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></script>'); 
}

if (typeof System == "undefined"
		|| !System.getProperty("excludeJsLoadingInPsgcommon")) {
	if (!isWindowsCE) {
		if (typeof window.jQuery == "undefined") {
			includeJavaScript('PSGLibrary/auf/lib/jquery-1.6.2.min.js');
			includeJavaScript('PSGLibrary/jquery.blockUI.js');
			includeJavaScript('PSGLibrary/auf/lib/jquery.multiselect-1.6.2.js');
			includeJavaScript('PSGLibrary/jquery.metadata.js');
			includeJavaScript('PSGLibrary/jquery.validate.js');
			includeJavaScript('PSGLibrary/jquery.ajax_upload.js');
			includeJavaScript('PSGLibrary/jquery.bgiframe.js');
			includeJavaScript('PSGLibrary/actionListener.js');
		}
	}
}


// Ennesima pezza per sistemare il delayed !!!
// Aggiunge a tutti i button il type='button', altrimenti f� il submit prima di settare l'azione
// nel metodo delayed...
if (typeof window.jQuery != "undefined") {
  if(!isIE){
    $(document).ready(function() {
      jQuery.ajaxSettings.traditional = true;
      $("button").each(function(){
    		this.type = 'button';  
	  });
    });
  }
}

//calculate the current window width //
function pageWidth() {
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// calculate the current window height //
function pageHeight() {
  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// calculate the current window vertical offset //
function topPosition() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// calculate the position starting at the left of the window //
function leftPosition() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

alertBoxHeader = function(icon, title, body, dialogwidth, dialogheight,header) {
	
	if(isWindowsCE){
		alert(body);
		return;
	}
	
	var width = pageWidth();
	var height = pageHeight();
	var left = leftPosition();
	var top = topPosition();
	var topposition = top + ((height - dialogheight) / 3);
	var leftposition = left + ((width - dialogwidth) / 2);
	
	 var txt = "";
	 txt += '<div style="width: ' + (dialogwidth-2) +'px; position: absolute; top: 0; left: 0; background: url(\'' + header + '\'); text-align: center; padding-top: 3px; padding-bottom: 3px;"><strong>' + title + '</strong></div>';
	 txt += '<div style="width: ' + (dialogwidth-2) +'px; position: absolute; top: 30; left: 5; text-align: left;"><img src="' + icon + '" alt="-" /></div>';
	 txt += '<div style="width: ' + (dialogwidth-72) +'px; position: absolute; top: 30; left: 70; text-align: left;"><div>' + body + '</div></div>';
	 txt += '<div style="width: ' + (dialogwidth-2) +'px; position: absolute; bottom: 0; left: 0; background: #ffffff; text-align: center; text-align: center; padding-top: 3px; padding-bottom: 3px;"><div>' + '<input class="BTN_FIXED" type="button" name="OkButton" value="OK" onClick="unlockUI()">' + '</div></div>';
	 $.blockUI({ message : txt, css: { margin: '0px', top: topposition + 'px', left: leftposition + 'px', position: 'absolute', width: dialogwidth + 'px', height: dialogheight + 'px', padding: '0px', background: '#ffffff', border: '1px solid #924949'}});
}

alertBox = function(icon, title, body, dialogwidth, dialogheight){
	alertBoxHeader(icon, title, body, dialogwidth, dialogheight,"images/error_header.gif");
}

//Tk 457627 Funzione richiamata sull'onmousedown di ogni bottone. Da implementare sulle singole jsp.
//E' nato dalla necessita di pulire tutti gli eventi onchange in modo che non si accavallino agli eventi
//onclick dei bottoni Es: $("*").attr("onchange","");
function buttonOnMouseDown()
{
	
}

//Tk 490660 Funzione chiamata sull'unLoad del body. Da implementare sulle singole jsp.
function onUnloadFunction()
{
	
}